<?php
namespace Admin\Model;

class TaskModel extends \Think\Model
{
	//自动验证
	protected $_validate = array(
		array('id', '/^[1-9]\d*$/', '请输入正确的任务ID', 1, 'regex', 2),
		array('name', '/^[\w\x{4e00}-\x{9fa5}]{2,}$/u', '请输入正确的任务名称', 1),
		array('title', '/^[\w\x{4e00}-\x{9fa5}]{2,}$/u', '请输入正确的任务标题', 1),
		array('type_id', '/^[1-9]\d*$/', '请输入正确的任务类型ID', 1, 'regex', 1),
		array('money', '/^\d|(0\.\d+)$/', '请输入正确的任务奖金', 1, 'regex', 1),
		array('start_time', '/^20\d{2}-(0[1-9]|1[012])-(0[1-9]|[1-2]\d|3[01])\s+([01]\d|2[0-3]):00$/', '任务开始时间格式错误', 1, 'regex', 1),
		array('end_time', '/^20\d{2}-(0[1-9]|1[012])-(0[1-9]|[1-2]\d|3[01])\s+([01]\d|2[0-3]):00$/', '任务结束时间格式错误', 2, 'regex', 1),
		array('description', 'require', '请输入任务描述', 1),
	);
	
	//自动完成
	protected $_auto = array(
		array('create_time', 'time', 1, 'function'),
		array('update_time', 'time', 3, 'function'),
		array('status', 1, 1, 'string')
	);
	
	/**
	 * 添加任务
	 * @author 刘新
	 */
	public function addTask()
	{
		$return = array('error' => 0, 'msg' => '添加成功');
		//数据对象判断
		if($this->create() === false) return array('error' => 1, 'msg' => $this->getError());
		$this->start_time = strtotime($this->start_time);
		$this->file_ids = implode(',', $this->file_ids);

		if($this->end_time) {
			$this->end_time = strtotime($this->end_time);
		} else {
			$this->end_time = 0;
		}
		
		//添加
		$res = $this->add();
		if($this->description!=""){
			$lastid = $this->getLastInsID();
			$description = $this->description;
			$description = '<meta charset="utf8">'.$description;
			filewrite("/data/www/qgh/Application/Home/View/App/".$lastid.".html",$description);
			$this->where(array("id"=>$lastid))->save(array("target_url"=>"http://114.215.209.229/Application/Home/View/App/".$lastid.".html"));
		}
		//添加结果判断
		if($res === false) {
			//添加失败，写入错误日志
			\Think\Log::record($this->getDbError(), 'WARN', true);
			$return['error'] = 1;
			$return['msg'] = $this->getDbError();
			return $return;
		}
		
		return $return;
	}
	
	/**
	 * 编辑任务
	 * @author 刘新
	 */
	public function editTask()
	{
		$return = array('error' => 0, 'msg' => '编辑成功');
		//数据对象判断
		if($this->create() === false) return array('error' => 1, 'msg' => $this->getError());
		$this->start_time = strtotime($this->start_time);
		$this->file_ids = implode(',', $this->file_ids);
		
		if($this->end_time) {
			$this->end_time = strtotime($this->end_time);
		} else {
			$this->end_time = 0;
		}
//		if($this->description!=""){
//			$description = $this->description;
//			$description = '<meta charset="utf8">'.$description;
//			filewrite("/data/www/qgh/Application/Home/View/App/".$this->id.".html",$description);
//			$this->target_url = "http://121.14.38.35/Application/Home/View/App/".$this->id.".html";
//		}
		//更新
		$res = $this->save();
		//更新结果判断
		if(!$res) {
			//更新失败，写入错误日志
			\Think\Log::record($this->getDbError(), 'WARN', true);
			$return['error'] = 1;
			$return['msg'] = $this->getDbError();
			return $return;
		}
	
		return $return;
	}
}